package com.qf.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qf.commons.TableData;
import com.qf.entity.EndUser;
import com.qf.exception.BizException;
import com.qf.mapper.EndUserDao;
import com.qf.service.EndUserService;
import com.qf.utils.ExportExcel;
import com.qf.utils.ImportExcel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;


@Service
public class EndUserServiceImpl implements EndUserService {
    @Value("${fileDownloadLocation}")
    private String fileDownloadLocation;

    private EndUserDao endUserDao;

    public EndUserServiceImpl(EndUserDao endUserDao) {
        this.endUserDao = endUserDao;
    }

    @Override
    public TableData<EndUser> QueryAll(Integer offset, Integer limit) throws BizException {
        TableData<EndUser> tableData = new TableData<>();
        Page<Object> page = null;
        List<EndUser> endUsers = null;
        QueryWrapper<EndUser> qw = new QueryWrapper<>();
        qw.ne("id",1);
        try {
            page = PageHelper.offsetPage(offset, limit);
            endUsers = endUserDao.selectList(qw);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("服务层查询错误");
        }
        tableData.setTotal(page.getTotal());
        tableData.setRows(endUsers);
        return tableData;
    }

    @Override
    public Integer changeUser(EndUser endUser) throws BizException {

        try {
            EndUser endUser1 = endUserDao.selectById(endUser.getId());
            if (endUser1 == null) {
                return 0;
            }
            Integer integer = endUserDao.updateUser(endUser);

            return integer;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("服务层修改错误");
        }
    }

    @Override
    public Integer insertUser(EndUser endUser) throws BizException {
        QueryWrapper<EndUser> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("end_name", endUser.getEndName());
        System.out.println(endUser);
        Integer insert = 0;
        try {
            List<EndUser> queryEndUser = endUserDao.selectList(objectQueryWrapper);
            System.out.println(queryEndUser);
            if (queryEndUser.size() > 1) {

                return insert;
            }
            insert = endUserDao.insert(endUser);
            return insert;
        } catch (Exception e) {
            throw new BizException("服务层添加错误");
        }
    }

    @Override
    public String generateExcel(String path) {
        String fullPath = null;
        try {
            List<EndUser> allEndUsers = endUserDao.selectList(Wrappers.emptyWrapper());

            String title = "后台用户信息";
            String[] rowNames = {"ID", "姓名", "密码", "状态", "权限"};

            List<Object[]> userObjs = new ArrayList<>();

            allEndUsers.forEach(u -> {
                Object[] obj = {
                        u.getId(),
                        u.getEndName(),
                        u.getEndPassword(),
                        1 == u.getState() ? "启用" : "禁用",
                        1 == u.getAdminuser() ? "超级用户" : "普通用户"
                };
                userObjs.add(obj);
            });

            ExportExcel exportExcel = new ExportExcel(title, rowNames, userObjs);

            //根据时间生成文件名  20200630164834.xls
//            String fileName = DateUtils.transferDateToStr(new Date(), DateUtils.DATE_KEY_STR) +
//            ".xls";
            fullPath = fileDownloadLocation + path;

            exportExcel.export(fullPath);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new BizException("业务层生成Excel异常: " + ex.getMessage());
        }
        return fullPath;
    }


    @Override
    public Integer fileToSql(String filePath) {
        ImportExcel importExcel = new ImportExcel();
        List<EndUser> userList = new ArrayList<>();
        Integer integer=0;
        try {
            List<Object[]> objList = importExcel.readExcelContent(new FileInputStream(filePath));
            objList.remove(0);
            objList.remove(0);
            for (Object[] obj : objList) {
                for (int i=0; i<obj.length ;i++)
                {
                    System.out.println(obj[i].toString());
                }
                EndUser endUser = new EndUser();

                if (obj[0] != null&&!"".equals(obj[0])){
                    String idString = obj[0].toString();
                    idString = idString.substring(0,idString.indexOf("."));
                    endUser.setId(Integer.valueOf(idString));
                }
                if (obj[1] != null&&!"".equals(obj[0]))
                    endUser.setEndName(obj[1].toString());
                if (obj[2] != null&&!"".equals(obj[0]))
                    endUser.setEndPassword(obj[2].toString());
                if (obj[3] != null&&!"".equals(obj[0]))
                    endUser.setState("启用".equals( obj[3]) ? 1 : 0);
                if (obj[4] != null&&!"".equals(obj[0]))
                    endUser.setAdminuser("超级用户".equals( obj[4]) ? 1 : 0);
                if (endUser.getEndName()!=null&&endUser.getEndPassword()!=null)
                    userList.add(endUser);
            }
            if (userList.size()>0){
                 integer= endUserDao.batchInsert(userList);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        userList.forEach(System.out::println);

        return integer;
    }
}
